//
//  SiginTodayController.m
//  签到
//
//  Created by Burn on 2018/12/13.
//  Copyright © 2018 nmgxysh. All rights reserved.
//

#import "SiginTodayController.h"
#import "SiginCellCollection.h"
#import "HeaderView.h"
#import "NSString+Base.h"
#import "DayModel.h"

#import "CalendarHeader.h"
@interface SiginTodayController ()<UICollectionViewDelegate,UICollectionViewDataSource>

/***/
@property(strong,nonatomic) UICollectionView *collectionView;

/***/
@property(strong,nonatomic) NSMutableArray *dataSource;

/**用户选择的当前年*/
@property(assign,nonatomic) NSInteger currentYear;

/**用户选择的当前月*/
@property(assign,nonatomic) NSInteger currentMonth;

/**用户选择的当前天*/
@property(assign,nonatomic) NSInteger currentDay;

/***/
@property(strong,nonatomic) HeaderView *dayView;


/**真是的的当前年*/
@property(assign,nonatomic) NSInteger year;

/**真是的的当前月*/
@property(assign,nonatomic) NSInteger month;

/**真是的当前天*/
@property(assign,nonatomic) NSInteger day;


@end

static NSString *ID = @"TodayCELLID";
static NSString *IDHeader = @"TodayCELLIDSectionHeader";
static CGFloat spacing = 0;
static CGFloat itemSpaccing = 2;
static CGFloat lineSpacing = 5;
static CGFloat itemMax = 7;

@implementation SiginTodayController

- (void)viewDidLoad {
    [super viewDidLoad];

    //  保存当前 月数
    [self gevValue];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerClass:[SiginCellCollection class] forCellWithReuseIdentifier:ID];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:IDHeader];
    [self.view addSubview:self.collectionView];
    [self dataSource];
}

- (void)gevValue{
    //  用户选择时间
    NSString *currentTime = [NSString getCurrentTimes];
    NSArray *timeArr = [currentTime componentsSeparatedByString:@" "];
    NSArray *dayArray = [timeArr[0] componentsSeparatedByString:@"-"];
    self.currentYear = [dayArray[0] integerValue];
    self.currentMonth = [dayArray[1] integerValue];
    self.currentDay = [dayArray[2] integerValue];
    //  真是时间
    self.year = self.currentYear;
    self.month = self.currentMonth;
    self.day = self.currentDay;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:IDHeader forIndexPath:indexPath];
        header.backgroundColor = [UIColor redColor];
        [header addSubview:self.dayView];
        
        NSString *title = @"";
        title = [title stringByAppendingString:[NSString stringWithFormat:@"%ld",self.currentYear]];
        title = [title stringByAppendingString:@"年"];
        title = [title stringByAppendingString:[NSString stringWithFormat:@"%ld",self.currentMonth]];
        title = [title stringByAppendingString:@"月"];
        _dayView.titleText = title;
        
        return header;
    }else{
        return nil;
    }
    
}



- (UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    SiginCellCollection *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    DayModel *model = self.dataSource[indexPath.item];
    cell.model = model;

    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    DayModel *model = self.dataSource[indexPath.item];
    
//    if (model.day != self.day || model.month != self.month) { return; }
    
    model.sigin = YES;
    SiginCellCollection *cell = (SiginCellCollection *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.model = model;
    [cell sigin];
}



- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.headerReferenceSize = CGSizeMake(0, 55);
        layout.minimumLineSpacing = lineSpacing;
        layout.minimumInteritemSpacing = itemSpaccing;
        layout.sectionInset = UIEdgeInsetsMake(spacing, spacing, spacing, spacing);
        CGFloat wh = (([UIScreen mainScreen].bounds.size.width - itemSpaccing * 2) - (itemMax - 1) * lineSpacing) / 7;
        layout.itemSize = CGSizeMake(wh,wh) ;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 500) collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
//        _collectionView.scrollEnabled = NO;
    }
    return _collectionView;
}
#pragma mark - 数据源
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
        
        //  本月一号是周几
        NSInteger weekday = [NSString getWeekDay:[self getcurrnetMonth]];
        //  上个月一共有几天
        NSInteger lastMonthValue = [self getLastMonthDayNum];
        //  本月有多少天
        NSInteger currentMonthDay = [NSString monthDayNum:[self getcurrnetMonth]];
        
        //  获取上一个 需要显示的日期
        if (weekday != 1) {
            for (NSInteger i = (lastMonthValue - (weekday - 1)) + 1 ; i <= lastMonthValue ; i++) {
                DayModel *model = [[DayModel alloc]init];
                model.year = self.currentMonth == 1 ? self.currentYear - 1 : self.currentYear;
                model.month = self.currentMonth == 1 ? 12 : self.currentMonth - 1;
                model.day = i;
                Solar *slar = [[Solar alloc]initWithYear:(int)self.currentYear
                                             andMonth:(int)model.month
                                               andDay:(int)model.day];
                Lunar *lunar = [CalendarDisplyManager obtainLunarFromSolar:slar];
                [CalendarDisplyManager resultWithLunar:lunar resultFormat:^(NSString *year, NSString *month, NSString *day) {
                    model.lunar = day;
                }];
                [_dataSource addObject:model];
            }
        }
        
        //  获取本月显示的日期
        for (int i = 1; i <= currentMonthDay; i++) {
            DayModel *model = [[DayModel alloc]init];
            model.year = self.currentYear;
            model.month = self.currentMonth;
            model.day = i;
            Solar *slar = [[Solar alloc]initWithYear:(int)model.year
                                            andMonth:(int)model.month
                                              andDay:(int)model.day];
            Lunar *lunar = [CalendarDisplyManager obtainLunarFromSolar:slar];
            [CalendarDisplyManager resultWithLunar:lunar resultFormat:^(NSString *year, NSString *month, NSString *day) {
                if (self.currentDay == i) {
                    model.lunar = self.year == self.currentYear && self.month == self.currentMonth  ? @"今天" : day;
                }else{
                    model.lunar = day;
                }
            }];
            [_dataSource addObject:model];
        }
        
        //  如果本月5行可以显示完全 那么没必要显示6行
        if (_dataSource.count <= 35) {
            //  接着下月头部
            NSInteger count = 35 - _dataSource.count;
            for (int i = 1; i <= count; i++) {
                DayModel *model = [[DayModel alloc]init];
                //  如果是12月 那么年是 当前年+1
                model.year = self.currentMonth == 12 ? self.currentYear + 1 : self.currentYear;
                model.month = self.currentMonth == 12 ? 1 : self.currentMonth + 1;
                model.day = i;
                Solar *slar = [[Solar alloc]initWithYear:(int)model.year
                                                andMonth:(int)model.month
                                                  andDay:(int)model.day];
                Lunar *lunar = [CalendarDisplyManager obtainLunarFromSolar:slar];
                [CalendarDisplyManager resultWithLunar:lunar resultFormat:^(NSString *year, NSString *month, NSString *day) {
                    model.lunar = day;
                }];
                [_dataSource addObject:model];
            }
            return _dataSource;
        }
        
        //  接着下月头部
        NSInteger count = 42 - _dataSource.count;
        for (int i = 1; i <= count; i++) {
            DayModel *model = [[DayModel alloc]init];
            //  如果是12月 那么年是 当前年+1
            model.year = self.currentMonth == 12 ? self.currentYear + 1 : self.currentYear;
            model.month = self.currentMonth == 12 ? 1 : self.currentMonth + 1;
            model.day = i;
            Solar *slar = [[Solar alloc]initWithYear:(int)model.year
                                            andMonth:(int)model.month
                                              andDay:(int)model.day];
            Lunar *lunar = [CalendarDisplyManager obtainLunarFromSolar:slar];
            [CalendarDisplyManager resultWithLunar:lunar resultFormat:^(NSString *year, NSString *month, NSString *day) {
                model.lunar = day;
            }];
            [_dataSource addObject:model];
        }
        
    }
    return _dataSource;
}

#pragma mark - 获取当前月的日期
- (NSDate *)getcurrnetMonth{
    NSString *formatterString = @"";
    formatterString = [formatterString stringByAppendingString:[NSString stringWithFormat:@"%ld",self.currentYear]];        // 年
    formatterString = [formatterString stringByAppendingString:@"-"];
    formatterString = [formatterString stringByAppendingString:[NSString stringWithFormat:@"%02ld",self.currentMonth]];        // 月
    formatterString = [formatterString stringByAppendingString:@"-"];
    formatterString = [formatterString stringByAppendingString:@"01"];             // 日
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    NSDate *usingDate = [formatter dateFromString:formatterString];
    return usingDate;
}
#pragma mark - 获取上一月的日期
- (NSInteger )getLastMonthDayNum{
    
    NSString *formatterString = @"";
    NSInteger lastMonth = self.currentMonth == 1 ? 12 :  self.currentMonth - 1;
    formatterString = [formatterString stringByAppendingString:[NSString stringWithFormat:@"%ld",self.currentYear]];                //  年
    formatterString = [formatterString stringByAppendingString:@"-"];
    formatterString = [formatterString stringByAppendingString:[NSString stringWithFormat:@"%02ld",lastMonth]];     //  月
    formatterString = [formatterString stringByAppendingString:@"-"];
    formatterString = [formatterString stringByAppendingString:@"01"];                          //  日
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    NSDate *usingDate = [formatter dateFromString:formatterString];
    
    return [NSString monthDayNum:usingDate];
}

#pragma mark - 头部视图
- (HeaderView *)dayView{
    if (!_dayView) {
        _dayView = [[HeaderView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 55)];
        NSString *title = @"";
        title = [title stringByAppendingString:[NSString stringWithFormat:@"%ld",self.currentYear]];
        title = [title stringByAppendingString:@"年"];
        title = [title stringByAppendingString:[NSString stringWithFormat:@"%ld",self.currentMonth]];
        title = [title stringByAppendingString:@"月"];
        _dayView.titleText = title;
    }
    return _dayView;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    self.currentYear = 2011;
    self.currentMonth = [self getRandomNumber:1 to:12];
    [self.dataSource removeAllObjects];
    self.dataSource = nil;
    [self.collectionView reloadData];
}

- (int)getRandomNumber:(int)from to:(int)to{
    return (int)(from + (arc4random() % (to - from + 1)));
}

@end
